package pl.szpadel.android.gadu;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.os.Environment;

// My own log. Can use both android log and file
public class AGLog {

	static private FileOutputStream sFile;
	
	static private boolean LOG_TO_FILE = false;
	static private boolean LOG_TO_LOGGER = true;
	
	static public void e(String tag, String msg) {
		if (LOG_TO_LOGGER) android.util.Log.e(tag, msg);
		wrtieToFile(tag, msg);
	}
	static public void i(String tag, String msg) {
		if (LOG_TO_LOGGER) android.util.Log.i(tag, msg);
		wrtieToFile(tag, msg);
	}
	static public void w(String tag, String msg) {
		if (LOG_TO_LOGGER) android.util.Log.w(tag, msg);
		wrtieToFile(tag, msg);
	}
	static public void d(String tag, String msg) {
		if (LOG_TO_LOGGER) android.util.Log.d(tag, msg);
		wrtieToFile(tag, msg);
	}
	static public void v(String tag, String msg) {
		if (LOG_TO_LOGGER) android.util.Log.v(tag, msg);
		wrtieToFile(tag, msg);
	}
	
	static private void wrtieToFile(String tag, String msg) {
		if (LOG_TO_FILE) {
			if (sFile == null) {
				// create dir
				File dir = new File(Environment.getExternalStorageDirectory(), "AndroidGadu");
				dir.mkdirs();
				File logFile = new File(dir, "log.txt");
				try {
					sFile = new FileOutputStream(logFile, true);
				} catch (FileNotFoundException e) {
					android.util.Log.e("Log", "can not create log file: " + e);
					LOG_TO_FILE = false;
					return;
				}
			}
		
			Date timestamp = new Date();
			String logMessage = timestamp.toString() + " " + tag + " " + msg + "\n";
			try {
				sFile.write(logMessage.getBytes());
			} catch (IOException e) {
				android.util.Log.e("Log", "can not wrtie to file: " + e);
				LOG_TO_FILE = false;
			}
		} // LOG_TO_FILE
	}
}
